package com.hrms.web.controller.tool;


import com.alibaba.fastjson2.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class HttpUtilsWechat {
    public static String getRequest(String httpurl) {



        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 关闭远程连接
        }

        return result;



    }

    /*
     * 获取openid
     * */
    public String getOpenid(String code) {
        // 调用接口必要的参数
        StringBuilder data = new StringBuilder();
        // 手动配置appid、secret;
        String appid = "YOUR_APPID";
        String secret = "YOUR_APPSECRET";

        data.append("appid=" + appid + "&");
        data.append("secret=" + secret + "&");
        data.append("js_code=" + code + "&");
        data.append("grant_type=" + "authorization_code");

        String response = HttpUtilsWechat.getRequest("https://api.weixin.qq.com/sns/jscode2session?" + data);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String openid = jsonObject.getString("openid");
        return openid;
    }

    /*
     * 获取sessionKey*/
    public String getSessionKey(String code) {
        // 调用接口必要的参数
        StringBuilder data = new StringBuilder();
        // 手动配置appid、secret;
        String appid = "YOUR_APPID";
        String secret = "YOUR_APPSECRET";

        data.append("appid=" + appid + "&");
        data.append("secret=" + secret + "&");
        data.append("js_code=" + code + "&");
        data.append("grant_type=" + "authorization_code");

        String response = HttpUtilsWechat.getRequest("https://api.weixin.qq.com/sns/jscode2session?" + data);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String sessionKey = jsonObject.getString("session_key");
        return sessionKey;
    }
    /*
    * 获取手机号phoneNumber
    * */
    public String getPhoneNumber(String code) {
        // 调用接口必要的参数
        StringBuilder data = new StringBuilder();
        // 手动配置appid、secret;
        String appid = "YOUR_APPID";
        String secret = "YOUR_APPSECRET";
        data.append("appid=" + appid + "&");
        data.append("secret=" + secret + "&");
        data.append("js_code=" + code + "&");
        data.append("grant_type=" + "authorization_code");
        //获取微信令牌
        String response = HttpUtilsWechat.getRequest("https://api.weixin.qq.com/sns/jscode2session?" + data);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String accessToken = jsonObject.getString("access_token");
        //获取手机号兑换密钥code
        String phoneUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        //封装请求体
        Map<String, String> params = new HashMap<>();
        params.put("code", code);
        //封装请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<Map<String, String>>(params, headers);
        //通过RestTemplate发送请求，获取到用户手机号码
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(phoneUrl, httpEntity, JSONObject.class);
        String errmsg = responseEntity.getBody().getString("errmsg");
        String phoneNumber;
        try {
            if (errmsg.equals("ok")) {
                JSONObject phoneInfoJson = responseEntity.getBody().getJSONObject("phone_info");
                phoneNumber = phoneInfoJson.getString("phoneNumber");
                return phoneNumber;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return phoneNumber = "error";
    }
}

